<template>
  <div>
    <el-table
      :data="weChatList"
      highlight-current-row
      header-align="center"
      max-height="410"
      size="small"
      tooltip-effect="dark"
      style="width: 98% ;min-height:410px;padding:0 10px 0 26px;border:#eeeeee" @row-click="handleModulesClick">
      <el-table-column
        prop="secret"
        width="70px"
        align="center"
        label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.headImg" alt="" style="width: 80px;height: 80px;" @error="imgError(scope.$index)">
        </template>
      </el-table-column>
      <el-table-column
        prop="nickName"
        align="center"
        width="110px"
        label="微信公众平台名称">
      </el-table-column>
      <el-table-column
        prop="appId"
        align="center"
        width="110px"
        label="微信公众平台 AppID">
      </el-table-column>
      <el-table-column prop="orgName"
                       label="运营机构" width="60" class="hhh">
      </el-table-column>
      <!-- <el-table-column prop="appSecret"
                       v-if="!noUpdate"
                       label="选择栏目" width="60" class="hhh">
      </el-table-column> -->
      <el-table-column label="操作"
                       
                       width="110px">
        <template slot-scope="scope">
          <el-button @click="updateNewspaper(scope.row)" type="text" size="small">修改</el-button>
          <el-button @click="deleteNewspaper(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="wzNav">
      <template>
        <div class="block">
          <el-pagination background
                         :page-sizes="[10]"
                         :page-size="100"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="total">
          </el-pagination>
        </div>
      </template>
    </div>
    <el-dialog
      title="修改微信信息"
      :visible.sync="dialogVisible"
      width="80%">
      <el-row>
        <el-col :span="20"  style="height:420px;">
          <el-form ref="weChat" :model="copyRow" :rules="weChat" size="small"
                   label-width="200px">
            <el-form-item label="微信公众平台名称:"  prop="nickName">
              <el-input size="small" v-model="copyRow.nickName"></el-input>
              <p class="input-tips">请与微信公众平台后台设置一致</p>
            </el-form-item>
            <el-form-item label="微信公众平台接口 Token:"  prop="token">
              <el-input size="small" v-model="copyRow.token"></el-input>
              <p class="input-tips">请与微信公众平台后台设置一致</p>
            </el-form-item>
            <el-form-item label="微信公众平台 AppID:"  prop="appId">
              <el-input size="small" v-model="copyRow.appId"></el-input>
            </el-form-item>
            <el-form-item label="微信公众平台 AppSecret:">
              <el-input size="small" v-model="copyRow.secret"></el-input>
            </el-form-item>
            <el-form-item label="上传头像:" style="margin-bottom:50px;">
              <el-upload size="small"
                :action="upload_img"
                :on-success="handleAvatarSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                limit="1">
                <img v-if="copyRow.headImg"  :src="upload_prefix + copyRow.headImg"  style="width: 80px" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="绑定流程:" prop="region" style="margin-top:60px;">
              <el-select size="small" v-model="copyRow.auditType" placeholder="请选择绑定流程" @change="changevalue">
                <el-option v-for="item in selectdatas" :key="item.codeValue" :value="item.codeValue" :label="item.codeName"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-form label-width="200px" size="small">
          <el-form-item label="运营机构:" style="margin-top:30px;">
            <el-col :span="20">
              <div>
                <div class="treeArea" style="padding-top: 10px;max-height: 30vh;overflow-y: auto;">

                  <el-tree ref='treeTwo' :data="treeData" :props="defaultProps" v-loading="loading" show-checkbox
                    @node-click="handleNodeClick" :expand-on-click-node='false' node-key="id" :highlight-current='true'
                    :default-expand-all='true'>
                  </el-tree>
                </div>

              </div>
            </el-col>
          </el-form-item>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveData">保存修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  weChatList,
  detailWeChat,
  deleteWeChat,
  updateWeChat
} from "@/api/systemManage/multistationManagement";

import { getOrgTree } from "@/api/systemManage/partJobManagement";
import demoImg from "@/assets/images/userDemo.jpg";
import Bus from "@/utils/eventTransfer.js";
import { compositeScach } from "@/api/systemManage/roleManagement";
export default {
  name: "multistation-weChat-list",
  props: {
    org: {
      type: [String]
    },
    noUpdate: {
      type: [Boolean]
    }
  },
  watch: {
    org: {
      handler: function(val, oldVal) {
        if (val !== oldVal) {
          this.getList(this.org);
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      // 绑定流程 开始
      selectdatas: [],
      listItems: {
        rowBounds: {
          // offset: 1,
          offset: 0,
          limit: 100
        },
        condition: [
          {
            property: "codeType",
            value: "WORK_FLOW",
            type: "EQ"
          },
          {
            property: "status",
            value: "0",
            type: "EQ"
          }
        ],
        sort: [
          {
            direction: "ASC",
            property: "orderNo"
          }
        ],
        fields: []
      },
      auditType: "",
      // 绑定流程 结束
      total: 0,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      dialogVisible: false,
      copyRow: {},
      postList: {
        sort: [{ direction: "DESC", property: "crtTime" }],
        rowBounds: {
          offset: 0,
          limit: 10
        },
        condition: [
          {
            property: "orgId",
            value: "",
            type: "EQ"
          },
          {
            property: "orgName",
            value: "",
            type: "EQ"
          }
        ]
      },
      weChat: {
        nickName: [
          { required: true, message: "请输入微信公众平台名称", trigger: "blur" }
        ],
        token: [
          {
            required: true,
            message: "请输入微信公众平台接口 Token",
            trigger: "blur"
          }
        ],
        appId: [
          {
            required: true,
            message: "请输入微信公众平台 AppID",
            trigger: "blur"
          }
        ]
      },
      weChatList: [],
      upload_img: process.env.BASE_API + "/zcmtask" + "/zcm/upload/pic",
      upload_prefix: process.env.BASE_API + "/videaapi"
    };
  },
  mounted() {
    Bus.$on("weChatList", data => {
      this.getList(this.org);
    });
    Bus.$on("dataName", data => {
      this.orgName = data[0].name;
      this.orgId = data[0].id;
    });
    const id = {
      id: this.$store.getters.orgId
    };
    getOrgTree(id).then(response => {
      this.treeData = response.data.data;
      // 默认给个组织机构ID
      // this.selectItem.selectOuinfoId = this.treeData[0].id
      // this.loading = false
      // this.activeName = 'newspaper'
    });
  },
  beforeMount() {
    this.selectdata();
  },
  methods: {
    changevalue(val) {
      console.log("11", val);
      let obj = {};
      obj = this.selectdatas.find(item => {
        return item.codeValue === val;
      });
      console.log("22", obj);
      this.auditType = obj.codeName;
    },
    // 加载下拉数据 绑定流程
    selectdata() {
      compositeScach(this.listItems).then(response => {
        this.selectdatas = response.data.data.records;
      });
    },
    handleModulesClick(row, event, column) {
      this.$emit("handlemodulesclick", row);
    },
    handleAvatarSuccess(res, file) {
      this.copyRow.headImg = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    beforeRemove(file, fileList) {
      if (file && file.status === "success") {
        //删除
        this.$confirm("确认删除该图片？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.copyRow.headImg = false;
          })
          .catch(error => {
            console.error(error);
          });
      }
    },
    // handleNodeClick(data, node) {
    //     this.selectItem.orgName = data.name
    //     let myArr = [{
    //       name: data.name,
    //       id: data.id
    //     }]
    //     Bus.$emit('dataName', myArr)
    //     this.selectItem.selectOuinfoId = data.id
    //   },
    saveData() {
      var form = "weChat";
      this.$refs[form].validate(valid => {
        if (valid) {
          this.dialogVisible = false;
          // this.weChat.orgIds = this.$refs.treeTwo.getCheckedKeys();
          this.copyRow.orgIds = this.$refs.treeTwo.getCheckedKeys();
          updateWeChat(this.copyRow).then(response => {
            if (response.data.statusCode === 200) {
              this.$message({
                message: "保存成功",
                type: "success"
              });
              this.getList(this.org);
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      });
    },
    updateNewspaper(row) {
      console.log("222");
      console.log(row);
      this.dialogVisible = true;
      let query = {
        rowBounds: {
          offset: 0,
          limit: 1
        },
        condition: [
          {
            property: "orgId",
            value: row.orgId,
            type: "EQ"
          },
          {
            property: "id",
            value: row.id,
            type: "EQ"
          }
        ]
      };
      detailWeChat(query).then(response => {
        if (response.data.statusCode === 200) {
          console.log("xiugai", response.data.data);
          this.$refs.treeTwo.setCheckedKeys(
            response.data.data.records[0].orgIds
          );
          this.$message({
            message: "查询成功",
            type: "success"
          });
          this.copyRow = response.data.data.records[0];
        } else {
          this.$message.error("查询失败");
        }
      });
    },
    deleteNewspaper(row) {
      const query = {
        id: row.id
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteWeChat(query).then(response => {
            if (response.data.statusCode === 200) {
              this.weChatList.splice(this.weChatList.indexOf(row), 1);
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.getList(this.org);
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    imgError(index) {
      console.log("啥", demoImg);
      this.weChatList[index].headImg = demoImg;
    },
    handleSizeChange(val) {
      this.postList = val;
      this.getList(this.org);
    },
    handleCurrentChange(val) {
      // this.postList.page = val;
      this.postList.rowBounds.offset =
        this.postList.rowBounds.limit * (val - 1);
      this.getList(this.org);
    },
    getList(org) {
      var that = this;
      this.postList.condition[0].value = this.org;

      this.postList.condition[1].value = this.orgName;
      weChatList(this.postList).then(response => {
        response.data.data.records.forEach(function(item, index) {
          if (item.headImg != "") {
            item.headImg = that.upload_prefix + item.headImg;
          }
        });

        this.weChatList = response.data.data.records;
        this.total = response.data.data.count;
        if (this.weChatList != "") {
          this.$emit("handlemodulesclick", this.weChatList[0]);
        }
      });
    },
    getTree() {
      this.loading = true;
      const id = {
        id: this.$store.getters.orgId
      };
      getOrgTree(id).then(response => {
        this.treeData = response.data.data;
        // 默认给个组织机构ID
        let self = this;
        this.selectItem.selectOuinfoId = this.treeData[0].id;

        this.loading = false;
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
